package com.bac.rentmap.ad.flat.proccess;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.beans.factory.annotation.Required;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.rating.FlatAdRatingCalculator;
import com.bac.rentmap.jdo.JdoSupport;
import com.google.appengine.api.memcache.MemcacheService;

/**
 * Calculates {@link FlatAd} rating.
 *
 * @author Andrew Osipenko
 */
public class RatingFlatAdProccessor extends JdoSupport implements
        FlatAdProccessor {
    private static final Logger log = Logger
            .getLogger(RatingFlatAdProccessor.class.getName());
    private int batchSize;
    private FlatAdRatingCalculator flatAdRatingCalculator;
    private MemcacheService cache2clear;

    public int proccess() {
        PersistenceManager persistenceManager = getPersistenceManager();
        try {
            Query query = buildQuery(persistenceManager);
            query.setRange(0, batchSize);
            @SuppressWarnings("unchecked")
            List<FlatAd> flatAds = (List<FlatAd>) query.execute();
            log.fine("Found " + flatAds.size() + " ads");
            for (FlatAd flatAd : flatAds) {
                flatAd.setRating(flatAdRatingCalculator.calculateRating(flatAd));
            }
            int res = flatAds.size();
            if(res > 0){
                cache2clear.clearAll();
            }
            return res;
        } finally {
            persistenceManager.close();
        }
    }

    @Required
    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    @Required
    public void setFlatAdRatingCalculator(
            FlatAdRatingCalculator flatAdRatingCalculator) {
        this.flatAdRatingCalculator = flatAdRatingCalculator;
    }

    public int getQueueSize() {
        PersistenceManager persistenceManager = getPersistenceManager();
        try {
            Query query = buildQuery(persistenceManager);
            query.setResult("count(this)");
            Object res = query.execute();
            if(res == null)
                return 0;
            return ((Number) res).intValue();
        } finally {
            persistenceManager.close();
        }
    }

    private Query buildQuery(PersistenceManager persistenceManager) {
        Query query = persistenceManager.newQuery(FlatAd.class);
        query.setFilter("ratingCalculated == false && agentCalculated == true");
        return query;
    }

    public int getBatchSize() {
        return batchSize;
    }

    @Required
    public void setCache2clear(MemcacheService cache2clear) {
        this.cache2clear = cache2clear;
    }
}
